﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace NXBSaiGon.Account
{
    public partial class ChangePassword : System.Web.UI.Page
    {
        private SqlConnection conn = new SqlConnection(ConfigurationManager
                                                        .ConnectionStrings["NXBSaiGonConnectionString1"]
                                                        .ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
        {
            if (Session["username"] != null)
            {
                bool testpass = KiemTraPass(Session["username"].ToString(), CurrentPassword.Text);
                if (testpass)
                {
                    if (NewPassword.Text == ConfirmNewPassword.Text)
                    {
                        string newpass = NewPassword.Text.ToString();
                        string user = Session["username"].ToString();
                        conn.Open();
                        SqlCommand cmd = new SqlCommand("   UPDATE KhachHang "
                                                            + "SET Password = '"+ newpass +"' "
                                                            + "WHERE Username = '" + user + "' ", conn);
                        int count = cmd.ExecuteNonQuery();
                        if (count != 0)
                            Response.Redirect("./ChangePasswordSuccess.aspx");
                        else
                            Result.Text = "Thay doi password bi loi.";
                        conn.Close();
                    }
                }
                else
                {
                    Result.Text = "nhap sai password hien tai.";
                }
            }
            else
            {
                Response.Redirect("./Login.aspx");
            }
        }

        private bool KiemTraPass(string user, string pass)
        {
            // mở kết nối để thực thi lệnh truy vấn
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM KhachHang " +
                                            "WHERE Username='" + user + "' AND Password='" + pass + "'", conn);
            int count = (int)cmd.ExecuteScalar();
            conn.Close();
            if (count != 0)
                return true;
            else
                return false;
            
        }
    }
}
